package thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DaYinJiOu {

    static volatile int count = 0;

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition ji = lock.newCondition();
        Condition ou = lock.newCondition();
        new Thread(() -> {
            while (count < 100) {
                lock.lock();
                if (count % 2 == 1) {
                    ++count;
                    System.out.println(Thread.currentThread().getId() + " " + count);
                    ou.signalAll();
                } else {
                    try {
                        ji.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.unlock();
            }
        }).start();
        new Thread(() -> {
            while (count < 100) {
                lock.lock();
                if (count % 2 == 0) {
                    ++count;
                    System.out.println(Thread.currentThread().getId() + " " + count);
                    ji.signalAll();
                } else {
                    try {
                        ou.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.unlock();
            }
        }).start();
    }
}
